<?php
namespace app\mouth\controller;
use app\mouth\common\Api;
use think\Db;
use lib\wxBizDataCrypt;
use think\facade\Cache;
use think\Collection;

class IndexApi extends Collection{
    public $APPID = 'wxdb29abf88a2ab5e9';
    public $AppSecret = 'ee8e3cd3e89f1acad9049a81999c53f2';
    public function __construct()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: POST,GET');
        parent::__construct();
    }
    /**
     *微信登录
     * code
     * @return \think\response\Json
     */
    public function login()
    {
        //开发者使用登陆凭证 code 获取 session_key 和 openid
        $APPID = $this->APPID;
        $AppSecret = $this->AppSecret;
        $code = input("code");
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $APPID . "&secret=" . $AppSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $arr = $this->vget($url);
        $arr = json_decode($arr, true);
        $openid = $arr['openid'];  //微信用户唯一标识
        $session_key = $arr['session_key'];
        $openids = Cache::get($openid);
        if (empty($openids)) {
//         数据签名校验
        $signature = input('signature');
        $rawData = input('rawData');
        $signature2 = sha1($rawData . $session_key);
        if ($signature != $signature2) {
            return json(['code' => 500, 'msg' => '数据签名验证失败！']);
        }
        $encryptedData = input("encryptedData");
        $iv = input("iv");
        $pc = new WXBizDataCrypt($APPID, $session_key);
        $errCode = $pc->decryptData($encryptedData,$iv,$data); //其中$data包含用户的所有数据
        $data = json_decode($errCode, true);
        if (!empty($data)) {
            $userInfo = [
                'openid' => $data['openId'],
                'nickname' => $data['nickName'],
                'avatarurl' => $data['avatarUrl'],
                'gender' => $data['gender'],
                'country' => $data['language'],
                'province' => $data['province'],
                'city' => $data['city'],
                'ctime' => time(),
            ];
            $uid = Db::name('wx_user')->field('id')->where('openid',$openid)->find();
//            //判断用户是否已经授权登录（没有则注册）
            if (empty($uid)) {
                $uid = Db::name('wx_user')->insertGetId($userInfo);
                //圈子注册
                $quan = [
                    'openid'    => $openid,
                    'portrait'  => $data['avatarUrl'],
                    'gender'    => $data['gender'],
                    'nickname'  => $data['nickName'],
                    'time'      => time(),
                ];
                $quanzi_id = Db::name('circle_user')->insertGetId($quan);
            } else {
                $quanzi_id = Db::name('circle_user')->field('id')->where('openid',$openid)->find();
            }
            $openids = [
                'user_id'       => $uid,
                'quanzi_id'     => $quanzi_id,
                'gender'        => $data['gender'],
                'portrait'      => $data['avatarUrl'],
                'nickname'      => $data['nickName'],
                'openid'        => $openid,
                'session_key'   => $session_key,
            ];

        } else {
            echo $errCode;//打印失败信息
        }
    }

        $openids['session_key'] = $session_key;
        Cache::set($openids['openid'], $openids, 60 * 60 * 24 * 7);
        return json(['code' => 40006, 'msg' => '登录成功', $openids]);
    }
    public function vget($url){
        $info=curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output= curl_exec($info);
        curl_close($info);
        return $output;
    }
}